package com.qu.visitmodel.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;

/**
 * Created by ququ1 on 2017/7/26.
 */

public class VideoPreviewPicture {

    public static Bitmap getPreviewPicture(Context context, String url) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();

        //获取网络视频
        retriever.setDataSource(url, new HashMap<String, String>());
        Bitmap bitmap = retriever.getFrameAtTime(1000);
        FileOutputStream outStream = null;
        try {
            outStream = new FileOutputStream(new File(context.getExternalCacheDir().getAbsolutePath() + "/" + "preview" + ".jpg"));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 10, outStream);
            outStream.close();
            retriever.release();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public Bitmap createVideoThumbnail(String url, int width, int height) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        int kind = MediaStore.Video.Thumbnails.MINI_KIND;
        try {
            if (Build.VERSION.SDK_INT >= 14) {
                retriever.setDataSource(url, new HashMap<String, String>());
            } else {
                retriever.setDataSource(url);
            }
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException ex) {
            // Assume this is a corrupt video file
        } catch (RuntimeException ex) {
            // Assume this is a corrupt video file.
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
                // Ignore failures while cleaning up.
            }
        }
        if (kind == MediaStore.Images.Thumbnails.MICRO_KIND && bitmap != null) {
            bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
                    ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        }
        return bitmap;
    }
}
